package net.sf.midollo.net.protocol.tunnel;

import java.io.IOException;

import net.sf.midollo.io.IOStream;
import net.sf.midollo.io.IOStreamConfig;
import net.sf.midollo.io.IOStreamConnectorFullDuplex;
import net.sf.midollo.io.IOStreamFactory;
import net.sf.midollo.io.IOUtils;
import net.sf.midollo.net.protocol.Protocol;

public class Tunnel implements Protocol {

  protected final IOStream ioDst;
  protected final IOStreamConnectorFullDuplex ioConnector;

  public Tunnel(IOStream ioSrc, IOStreamFactory ioStreamFactory, int bufSizeRequest, int bufSizeResponse) throws IOException {
    this.ioDst = ioStreamFactory.open();
    if (ioDst instanceof IOStreamConfig) {
      IOStreamConfig ioDistConfig = (IOStreamConfig)this.ioDst;
      ioDistConfig.config(ioSrc);
    }
    IOStream[] ioStreams = IOUtils.connectFullDuplex(ioSrc, this.ioDst);
    this.ioConnector = new IOStreamConnectorFullDuplex(ioStreams, bufSizeRequest, bufSizeResponse);
  }

  public IOException getError() {
    return this.ioConnector.getError();
  }

  public void run() {
    this.ioConnector.run();
  }

  public void disconnect() throws IOException {
    this.ioDst.close();
  }
}
